package controllers;

import connectivity.Dbmanager;
import connectivity.QueryManager;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import models.Course;
import models.User;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

public class ManageDocumentsController extends HttpServlet {

    private Dbmanager dbManager;
    private QueryManager queryManager;
    LinkedList<Course> courses;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
            String baseDir = "C:/PDL/";
            if(request.getParameter("action") != null){
                if(request.getParameter("action").equals("delete")){
                    File f=new File(baseDir + request.getParameter("file"));
                    f.delete();
                } else if(request.getParameter("action").equals("rename")){
                    File f=new File(baseDir + request.getParameter("file"));
                    f.renameTo(new File(baseDir + request.getParameter("target")));
                } else if(request.getParameter("action").equals("newFolder")){
                    File file = new File(baseDir + request.getParameter("file"));
                    if(!file.exists()){
                        file.mkdirs();
                    }                    
                }
            }else {
                dbManager = new Dbmanager();
                dbManager.openConnection();
                queryManager = new QueryManager(dbManager);

                courses = new LinkedList<Course>();
                courses = queryManager.getAllCourses();
                
                HttpSession sessie = request.getSession();  
                LinkedList<Course> teacherCourses = queryManager.getAllTeacherCourses(Integer.parseInt(sessie.getAttribute("userId").toString()));
                
                Boolean courseManager;
                for(Course course : courses){ // Controleren over de leraar de course beheert 
                        if(!sessie.getAttribute("userLevel").toString().equals("3")){
                            courseManager = false;
                            for(Course teacherCourse : teacherCourses){
                                if(course.getCourseID() == teacherCourse.getCourseID()){
                                    courseManager = true;
                                }
                            }
                            if(courseManager == false){ // Als de leraar deze course niet mag beheren, deze verwijderen van de lijst
                                courses.remove(course);
                            }
                        }    
                }                

                request.setAttribute("courses", courses); 

                String address = "/manage_documents.jsp";
                dbManager.closeConnection();
                RequestDispatcher dispatcher = request.getRequestDispatcher(address);
                dispatcher.forward(request, response); //Stuurt door naar de Gebruikers index
            }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }    
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String baseDir = "C:/PDL/";
        File repository=new File(baseDir+request.getParameter("ID")+"/");
        
        try {
            DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();

//set temporary dir where uploaded files will be stored
            diskFileItemFactory.setRepository(repository);
//set the file size threshold beyond from which file will be stored in the disk
            diskFileItemFactory.setSizeThreshold(5*1024*1024);

//initialize form handler
            ServletFileUpload servletFileUpload= new ServletFileUpload(diskFileItemFactory);
        final PrintWriter writer = response.getWriter();
               
//get form fields
            List<FileItem> uploadedItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : uploadedItems) {

//if file item is a normal form filed take some action
                if(fileItem.isFormField()){
                    String fieldName = fileItem.getFieldName();
                    writer.write("FIELDNAME:"+fieldName);
                }else{
                    String name = fileItem.getName();
                    writer.write("NAME:"+name);
                    File uploadedFile=new File(repository.getAbsolutePath()+"\\"+name);
                    fileItem.write(uploadedFile);
                }
            }
           writer.close(); 
        } catch (Exception ex) {
            //Logger.getLogger(FileUploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {            
            out.close();
        }
    }
}